package kgame5.k25d.core {
	import kgame5.k25d.Util25D;
	import kgame5.k3d.core.math.Vector3D;
	import kgame5.kgui.GP;
	import kgame5.kutil.T;

	import flash.display.DisplayObject;
	import flash.display.Sprite;

	/**
	 * @author max
	 * 2010-12-19
	 * 
	 * 25D的网格，根据参数的集合信息和拓扑信息来画线组成图
	 */
	public class Mesh25D extends Node25D{
		private var mc:Sprite;
		
		private var arrVertex:Array;//Vector3D
		private var arrLine:Array;//哪几个定点组成一个面
		
		private var arrScreen:Array;//屏幕坐标
		
		private var arrColor:Array;
		
		//参数arrVertex是[x,y,z,x1,y1,z1....]
		public function Mesh25D(arrVertex:Array,arrLine:Array,arrColor:Array=null){
			this.mc=new Sprite();
			
			var vertexCount:int=arrVertex.length/3;
			
			this.arrVertex=new Array();
			
			for(var k:int=0;k<vertexCount;k++){
				this.arrVertex.push(new Vector3D(arrVertex[k*3],arrVertex[k*3+1],arrVertex[k*3+2]));
			}
			
			this.arrLine=arrLine;
			
			this.arrColor=arrColor;
			if(arrColor==null){
				this.arrColor=new Array();
				for(var j:int=0;j<arrLine.length/2;j++){
					this.arrColor[j]=0xff0000;
				}
			}
			
			arrScreen=new Array();
			for(var i:int=0;i<vertexCount;i++){
				arrScreen.push(new Vector3D());
			}
		}
		override public function getDO():DisplayObject{
			return mc;
		}
		
		//从3D空间向屏幕投影
		override public function update(camera:Camera25D):void{
			if(visible==false){
				return;
			}
			getDO().visible=true;//先显示
			
			//清除老的
			mc.graphics.clear();
			
			
			//把每个点都在本图形自己的坐标系内投影好
			for (var i:int=0;i<arrVertex.length;i++){
				var v:Vector3D=arrVertex[i];
				var s:Vector3D=arrScreen[i];
				
				Util25D.worldToScreen(v, s);
			}
			
			//画线
			for (var i:int=0;i<arrLine.length;i+=2){
				var idxA:int=arrLine[i];
				var idxB:int=arrLine[i+1];
				
				var color:uint=arrColor[i/2];
				
				GP.drawLine(mc.graphics, color, arrScreen[idxA].x, arrScreen[idxA].y, arrScreen[idxB].x, arrScreen[idxB].y);
			}
			
			//整体的位置
			Util25D.worldToScreen(spcVO.v3d_p, v3d_screen);
			
			getDO().x=v3d_screen.x;
			getDO().y=v3d_screen.y;
			
			depth=v3d_screen.z;
			
			if(camera.canCull(getDO())){//如果出了屏幕，则不显示
				getDO().visible=false;//
			}
			
		}
	}
}
